<template>
  <div class="pdf-viewer-container">
    <!-- 顶部控制栏 -->
    <div class="control-bar">
      <div class="search-section">
        <input
          v-model="searchText"
          placeholder="输入要搜索的文本..."
          @keyup.enter="searchTextInPdf"
          class="search-input" />
        <button @click="searchTextInPdf" class="search-btn">搜索并高亮</button>
      </div>

      <div class="navigation-section">
        <button
          @click="prevPage"
          :disabled="currentPage <= 1"
          class="nav-btn">
          上一页
        </button>
        <span class="page-info">页码: {{ currentPage }} / {{ totalPages }}</span>
        <button
          @click="nextPage"
          :disabled="currentPage >= totalPages"
          class="nav-btn">
          下一页
        </button>
      </div>

      <div class="scale-control">
        <span>缩放: </span>
        <select v-model="scale" @change="renderAllPages" class="scale-select">
          <option value="1">100%</option>
          <option value="1.25">125%</option>
          <option value="1.5">150%</option>
          <option value="2">200%</option>
        </select>
      </div>
    </div>

    <!-- 搜索结果信息 -->
    <div v-if="searchResults.length > 0" class="search-results-info">
      <span>找到 {{ searchResults.length }} 个匹配项</span>
      <div class="highlight-nav">
        <button
          @click="scrollToPrevHighlight"
          :disabled="currentHighlight <= 0"
          class="highlight-btn">
          上一个
        </button>
        <button
          @click="scrollToNextHighlight"
          :disabled="currentHighlight >= searchResults.length - 1"
          class="highlight-btn">
          下一个
        </button>
      </div>
    </div>

    <!-- PDF显示区域 -->
    <div class="pdf-viewport">
      <div v-if="loading" class="loading-indicator">
        <div class="spinner"></div>
        <p>正在加载PDF文档...</p>
      </div>

      <div v-else class="pdf-pages">
        <div
          v-for="page in pages"
          :key="page.pageNumber"
          :id="`page-${page.pageNumber}`"
          class="page-container">
          <canvas :id="`pdf-canvas-${page.pageNumber}`" class="pdf-canvas"></canvas>
          <div :id="`text-layer-${page.pageNumber}`" class="text-layer"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 设置PDF.js worker路径
import * as pdfjsLib from 'pdfjs-dist'
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js';

export default {
  name: 'PdfViewerDemo',

  data () {
    return {
      pdfDoc: null,
      currentPage: 1,
      totalPages: 0,
      loading: true,
      searchText: '',
      searchResults: [],
      currentHighlight: -1,
      pages: [],
      scale: 1.5
    };
  },

  mounted () {
    this.loadPdf();
  },

  methods: {
    // 加载PDF文档
    async loadPdf () {
      try {
        this.loading = true;
        // 使用示例PDF文档
        const url = '3.pdf';

        this.pdfDoc = await pdfjsLib.getDocument({
          url,
          cMapUrl: '/cmaps/',
          cMapPacked: true
        }).promise;
        this.totalPages = this.pdfDoc.numPages;

        // 初始化页面数组
        this.pages = Array.from({ length: this.totalPages }, (_, i) => ({
          pageNumber: i + 1,
          rendered: false
        }));
        this.pages.forEach(page => {
          // 渲染第一页
          this.renderPage(page.pageNumber);
        })
      } catch (error) {
        console.error('Error loading PDF:', error);
        this.$emit('error', error);
      } finally {
        this.loading = false;
      }
    },

    // 渲染指定页面
    async renderPage (pageNum) {
      try {
        const page = await this.pdfDoc.getPage(pageNum);
        const viewport = page.getViewport({ scale: this.scale });

        const canvas = document.getElementById(`pdf-canvas-${pageNum}`);
        const context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        await page.render({
          canvasContext: context,
          viewport: viewport
        }).promise;

        // 设置 CSS 变量
        const pageContainer = document.getElementById(`page-${pageNum}`);
        if (pageContainer) {
          pageContainer.style.setProperty('--scale-factor', this.scale);
        }

        await this.renderTextLayer(page, pageNum, viewport);

        const pageIndex = this.pages.findIndex(p => p.pageNumber === pageNum);
        if (pageIndex !== -1) {
          this.pages[pageIndex].rendered = true;
        }
      } catch (error) {
        console.error('Error rendering page:', error);
        this.$emit('error', error);
      }
    },

    // 重新渲染所有页面（用于缩放改变时）
    async renderAllPages () {
      for (let i = 1; i <= this.totalPages; i++) {
        if (this.pages[i - 1].rendered) {
          await this.renderPage(i);
        }
      }

      // 如果存在搜索结果，重新应用高亮
      if (this.searchResults.length > 0) {
        this.searchTextInPdf();
      }
    },

    // 渲染文本层
    async renderTextLayer (page, pageNum, viewport) {
      const textLayerDiv = document.getElementById(`text-layer-${pageNum}`);
      textLayerDiv.style.width = `${viewport.width}px`;
      textLayerDiv.style.height = `${viewport.height}px`;

      // 获取文本内容
      const textContent = await page.getTextContent();

      // 清除之前的文本层内容
      textLayerDiv.innerHTML = '';

      // 渲染文本层
      pdfjsLib.renderTextLayer({
        textContent: textContent,
        container: textLayerDiv,
        viewport: viewport,
        textDivs: []
      });
    },

    // ========== 新增：跨 span 搜索工具函数 ==========
    getPageTextMap (pageNum) {
      const textLayer = document.getElementById(`text-layer-${pageNum}`);
      if (!textLayer) return { fullText: '', spanMap: [] };

      const spans = textLayer.querySelectorAll('span');
      let fullText = '';
      const spanMap = [];

      spans.forEach(span => {
        const text = span.textContent;
        spanMap.push({ span, start: fullText.length, end: fullText.length + text.length, text });
        fullText += text;
      });
      return { fullText, spanMap };
    },

    searchAcrossSpans (pageNum, keyword) {
      const { fullText, spanMap } = this.getPageTextMap(pageNum);
      const results = [];
      if (!keyword) return results;

      let idx = fullText.indexOf(keyword);
      while (idx !== -1) {
        const matchStart = idx;
        const matchEnd = idx + keyword.length;

        // 收集所有与这段区间重叠的 span
        const touched = spanMap.filter(
          s => s.start < matchEnd && s.end > matchStart
        );
        results.push({ page: pageNum, touched, matchStart, matchEnd });
        idx = fullText.indexOf(keyword, idx + 1);
      }
      return results;
    },

    highlightMatches (matches, keyword) {
      matches.forEach(({ touched, matchStart, matchEnd }) => {
        touched.forEach(({ span, start: spanStart, text }) => {
          const relStart = Math.max(0, matchStart - spanStart);
          const relEnd = Math.min(text.length, matchEnd - spanStart);

          if (relStart >= text.length || relEnd <= 0) return;

          const before = text.slice(0, relStart);
          const hit = text.slice(relStart, relEnd);
          const after = text.slice(relEnd);

          // 用 <mark> 做高亮，方便清除
          span.innerHTML = `${before}<mark class="text-highlight">${hit}</mark>${after}`;
        });
      });
    },
    // ========== 工具函数结束 ==========

    // 搜索PDF中的文本
    async searchTextInPdf () {
      // 1. 清空旧结果
      this.clearHighlights();
      this.searchResults = [];
      if (!this.searchText.trim()) return;

      // 2. 逐页搜索
      for (let p = 1; p <= this.totalPages; p++) {
        // 保证文本层已渲染
        if (!this.pages[p - 1].rendered) await this.renderPage(p);

        const pageMatches = this.searchAcrossSpans(p, this.searchText);
        if (pageMatches.length) {
          // 记录结果（用于翻页跳转）
          this.searchResults.push(...pageMatches.map(m => ({ page: m.page })));
          // 真正高亮
          this.highlightMatches(pageMatches, this.searchText);
        }
      }

      // 3. 无结果提示
      if (this.searchResults.length === 0) {
        this.$emit('no-results', this.searchText);
      } else {
        this.currentHighlight = 0;
        this.scrollToCurrentHighlight();
      }
    },

    // 清除所有高亮
    clearHighlights () {
      document.querySelectorAll('.text-highlight').forEach(mark => {
        const parent = mark.parentNode;
        parent.replaceChild(document.createTextNode(mark.textContent), mark);
        parent.normalize(); // 合并相邻文本节点
      });
      this.searchResults = [];
      this.currentHighlight = -1;
    },

    // 高亮搜索结果
    highlightSearchResults () {
      // 现由 searchTextInPdf 直接完成，此方法留空即可
    },

    // 滚动到当前高亮
    scrollToCurrentHighlight () {
      if (this.currentHighlight < 0 || this.currentHighlight >= this.searchResults.length) return;

      const result = this.searchResults[this.currentHighlight];
      const pageElement = document.getElementById(`page-${result.page}`);

      if (pageElement) {
        // 滚动到对应页面
        this.currentPage = result.page;
        pageElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
    },

    // 滚动到上一个高亮
    scrollToPrevHighlight () {
      if (this.currentHighlight > 0) {
        this.currentHighlight--;
        this.scrollToCurrentHighlight();
      }
    },

    // 滚动到下一个高亮
    scrollToNextHighlight () {
      if (this.currentHighlight < this.searchResults.length - 1) {
        this.currentHighlight++;
        this.scrollToCurrentHighlight();
      }
    },

    // 上一页
    prevPage () {
      if (this.currentPage > 1) {
        this.currentPage--;
        if (!this.pages[this.currentPage - 1].rendered) {
          this.renderPage(this.currentPage);
        }
        this.scrollToPage(this.currentPage);
      }
    },

    // 下一页
    nextPage () {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
        if (!this.pages[this.currentPage - 1].rendered) {
          this.renderPage(this.currentPage);
        }
        this.scrollToPage(this.currentPage);
      }
    },

    // 滚动到指定页面
    scrollToPage (pageNum) {
      const pageElement = document.getElementById(`page-${pageNum}`);
      if (pageElement) {
        pageElement.scrollIntoView({ behavior: 'smooth' });
      }
    }
  },

  watch: {
    // 监听当前页变化
    currentPage (newPage, oldPage) {
      if (newPage !== oldPage && !this.pages[newPage - 1].rendered) {
        this.renderPage(newPage);
      }
    }
  }
};
</script>

<style scoped>
.pdf-viewer-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.control-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f5f7fa;
  border-bottom: 1px solid #e0e6ed;
  flex-wrap: wrap;
  gap: 15px;
}

.search-section {
  display: flex;
  flex: 1;
  min-width: 300px;
  max-width: 500px;
}

.search-input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #d1d8e0;
  border-radius: 6px 0 0 6px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
}

.search-input:focus {
  border-color: #4b6cb7;
}

.search-btn {
  padding: 10px 20px;
  background: #4b6cb7;
  color: white;
  border: none;
  border-radius: 0 6px 6px 0;
  cursor: pointer;
  font-weight: 600;
  transition: background 0.3s;
}

.search-btn:hover {
  background: #3a5795;
}

.navigation-section {
  display: flex;
  align-items: center;
  gap: 10px;
}

.nav-btn {
  padding: 8px 15px;
  background: #5a81d1;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.3s;
}

.nav-btn:hover:not(:disabled) {
  background: #4b6cb7;
}

.nav-btn:disabled {
  background: #c3cfe2;
  cursor: not-allowed;
}

.page-info {
  font-weight: 600;
  color: #4b6cb7;
  min-width: 100px;
  text-align: center;
}

.scale-control {
  display: flex;
  align-items: center;
  gap: 8px;
}

.scale-select {
  padding: 8px;
  border: 1px solid #d1d8e0;
  border-radius: 4px;
  outline: none;
}

.search-results-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background: #e6f7ff;
  border-bottom: 1px solid #bae7ff;
  color: #1890ff;
  font-weight: 500;
}

.highlight-nav {
  display: flex;
  gap: 10px;
}

.highlight-btn {
  padding: 6px 12px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: background 0.3s;
}

.highlight-btn:hover:not(:disabled) {
  background: #0c7cd5;
}

.highlight-btn:disabled {
  background: #91d5ff;
  cursor: not-allowed;
}

.pdf-viewport {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #eaedf2;
  position: relative;
}

.loading-indicator {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 300px;
  color: #4b6cb7;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(75, 108, 183, 0.2);
  border-radius: 50%;
  border-top-color: #4b6cb7;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.pdf-pages {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.page-container {
  position: relative;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
  background: white;
}

.pdf-canvas {
  display: block;
}

.text-layer {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  overflow: hidden;
  opacity: 0.2;
  line-height: 1.0;
  pointer-events: none;
}

.text-layer ::v-deep span {
  color: transparent;
  position: absolute;
  white-space: pre;
  cursor: text;
  transform-origin: 0% 0%;
  pointer-events: auto;
}

/* 高亮颜色 */
.text-layer ::v-deep .text-highlight {
  background: red;
  border-radius: 4px;
}

@media (max-width: 768px) {
  .control-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-section {
    max-width: 100%;
  }

  .navigation-section {
    justify-content: center;
  }

  .search-results-info {
    flex-direction: column;
    gap: 10px;
  }
}
</style>